<template>
  <resize-drawer
    :title="type === 'add' ? '新建事件推送' : '编辑事件推送'"
    :drawer="show"
    :size="576"
    :isShowMoreBtn="true"
    @onCloseDraw="closeDrawer"
    @onCancelFun="closeDrawer"
    @onSave="saveEvent"
  >
    <template #column>
      <el-form class="m7-form" :model="form" :rules="rules" ref="formRef" label-position="top" size="mini">
        <el-form-item label="事件类型" prop="type">
          <el-select filterable size="mini" v-model="form.eventType" placeholder="请选择">
            <el-option v-for="item in typeArr" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="推送地址" prop="pushUrl">
          <el-input size="mini" v-model.trim="form.pushUrl" placeholder="url必须要包含协议头http(s)://"></el-input>
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input
            size="mini"
            type="textarea"
            v-model.trim="form.description"
            placeholder="请输入说明"
            autosize
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
  </resize-drawer>
</template>

<script lang="ts">
import { defineComponent, reactive, getCurrentInstance, toRefs, nextTick } from 'vue'
import resizeDrawer from '@common/components/resize-drawer/index.vue'
import { urlValidate } from '@/common/utils/validate'
import { ElMessage } from 'element-plus'
import { deepClone } from '@/common/utils/common'
interface State {
  form: any
  rules: Record<string, unknown>
  type: string
  show: boolean
}
const defaultForm = {
  _id: '',
  eventType: '',
  pushUrl: '',
  description: ''
}
export default defineComponent({
  name: 'AddOrEditEvent',
  components: { resizeDrawer },
  emiits: ['onRefresh'],
  props: {
    typeArr: {
      type: Array,
      default: () => []
    }
  },
  setup(props, { emit }) {
    const instance: any = getCurrentInstance()
    const validateHttp = (rule: any, value: string, callback: Function) => {
      // 检测Url是否规范
      if (value !== '') {
        if (!urlValidate(value)) {
          callback(new Error('请输入正确的推送地址'))
        } else {
          callback()
        }
      } else {
        callback(new Error('请输入正确的推送地址'))
      }
    }
    const state: State = reactive({
      form: deepClone(defaultForm),
      rules: {
        pushUrl: [{ required: true, validator: validateHttp, trigger: 'blur' }]
      },
      type: 'add',
      show: false
    })
    // 打开或者是关闭抽屉 || 父级调用
    const openOrCloseDrawer = (data: any) => {
      state.show = !state.show
      handleForm(data)
    }
    // 关闭抽屉
    const closeDrawer = () => {
      state.show = false
    }
    // 整理表单
    const handleForm = (data: any) => {
      // 打开抽屉时，整理form数据
      if (data) {
        // 编辑
        Object.keys(data).forEach((key) => {
          if (state.form[key] !== undefined) {
            state.form[key] = data[key]
          }
        })
        state.type = 'edit'
      } else {
        // 新增重置表单
        state.type = 'add'
        state.form = deepClone(defaultForm)
      }
    }
    // 保存事件表单
    const saveEvent = () => {
      instance?.refs.formRef.validate((valid: boolean) => {
        if (valid) {
          const actionFrom = deepClone(state.form)
          if (state.type === 'add') {
            delete actionFrom._id
          }
          console.log(actionFrom, '===接口有了就发请求吧')
          emit('onRefresh', state.type === 'add' ? 'addSuccess' : null) // 外抛给父组件，用来刷新到第一页
          closeDrawer()
          ElMessage({ message: '保存成功', type: 'success' })
        } else {
          return false
        }
      })
    }

    return {
      saveEvent,
      openOrCloseDrawer,
      closeDrawer,
      ...toRefs(state)
    }
  }
})
</script>
<style lang="stylus" scoped>
.el-select
  width 100%
</style>
